﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using KongMing.Common;
using static System.Threading.Thread;
using static System.Console;

namespace Project_7
{
    /// <summary>
    /// 7.2 使用Parallel类
    /// </summary>
    public class Unit_7_02:UnitBase
    {
        public static void Go()
        {
            Parallel.Invoke(
                () => EmulateProcessing("Task1"),
                () => EmulateProcessing("Task2"),
                () => EmulateProcessing("Task3")
            );

            var cts=new CancellationTokenSource();
            var result = Parallel.ForEach(Enumerable.Range(1, 30), new ParallelOptions
            {
                CancellationToken = cts.Token,
                MaxDegreeOfParallelism = Environment.ProcessorCount,
                TaskScheduler = TaskScheduler.Default
            }, (i, state) =>
            {
                WriteLine(i);
                if (i == 20)
                {
                    state.Break();
                    WriteLine($"Loop is stopped:{state.IsStopped}");
                }
            });
            WriteLine("------");
            WriteLine($"IsCompleted:{result.IsCompleted}");
            WriteLine($"Lowest break iteration:{result.LowestBreakIteration}");
        }

        static string EmulateProcessing(string taskName)
        {
            Sleep(TimeSpan.FromMilliseconds(new Random(DateTime.Now.Millisecond).Next(250,350)));
            WriteCurrentTaskInfo(taskName);
            return taskName;
        }
    }
}
